<template>
  <div class="login-container">
    <h1>二手交易平台</h1>
    <div class="form-container">
      <div class="input-group">
        <label for="username">用户名:</label>
        <input
            type="text"
            id="username"
            v-model="username"
            placeholder="请输入用户名"
        />
      </div>
      <div class="input-group">
        <label for="password">密码:</label>
        <input
            type="password"
            id="password"
            v-model="password"
            placeholder="请输入密码"
        />
      </div>
      <div class="button-group">
        <button @click="handleLogin" class="login-btn">登录</button>
        <button @click="handleRegister" class="register-btn">注册</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios'; // 引入 axios
import { useRouter } from 'vue-router'; // 引入路由

// 定义响应式数据
const username = ref('');
const password = ref('');
const router = useRouter();

// 表单验证
const validateForm = () => {
  if (!username.value || !password.value) {
    alert('用户名和密码不能为空！');
    return false;
  }
  if (password.value.length < 6) {
    alert('密码长度不能小于 6 位！');
    return false;
  }
  return true;
};

// 处理登录逻辑
const handleLogin = async () => {
  if (!validateForm()) return;

  try {
    const response = await axios.post('http://localhost:9090/user/login', {
      userName: username.value,
      password: password.value,
    });

    // 调试输出响应结构
    console.log('登录响应:', response.data);

    if (response.data.code === 200) {
      // 确认 token 字段位置（假设实际在 response.data.token）
      const token = response.data.data || response.data.token;
      sessionStorage.setItem('token', token);

      // 强制刷新路由守卫
      await router.push({ path: '/index/recommend', replace: true });

      // 解决页面未更新问题
      window.location.reload();
    } else {
      alert('登录失败：' + (response.data.msg || '未知错误'));
    }
  } catch (error) {
    // 显示详细错误信息
    alert(`请求失败：${error.response?.data?.message || error.message}`);
  }
};

// 处理注册逻辑
const handleRegister = async () => {
  if (!validateForm()) return;

  try {
    const response = await axios.post('http://localhost:9090/user/registeer', {
      userName: username.value,
      password: password.value,
    });
    if (response.data.code===200) {
      alert('注册成功！');
    } else {
      alert('注册失败，'+response.data.msg);
    }
  } catch (error) {
    alert('请求失败，请稍后重试！');
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f5f5f5;
  font-family: Arial, sans-serif;
}

h1 {
  margin-bottom: 20px;
  color: #333;
}

.form-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 300px;
}

.input-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.login-btn {
  background-color: #42b983;
  color: #fff;
}

.login-btn:hover {
  background-color: #3aa876;
}

.register-btn {
  background-color: #f0ad4e;
  color: #fff;
}

.register-btn:hover {
  background-color: #eea236;
}
</style>